//
//  NewsDetailController.swift
//  SCA
//
//  Created by tjun on 2025/9/14.
//

import UIKit
import Kingfisher
import WebKit


class NewsDetailController: BaseController {
    
    let model: NewsListModel
    private lazy var progressView = GradientProgressView()
    private lazy var webView = WKWebView()

    init(model: NewsListModel) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if model.displayType == "pdf" {
            addWebView()
        } else {
            addScrollView()
        }
    }
    
    func addScrollView() {
        
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: navBarHeight, width: view.width, height: view.height - navBarHeight)).addTo(view)
        scrollView.keyboardDismissMode = .onDrag
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.contentInsetAdjustmentBehavior = .never
        
        var contentSize = CGSize(width: scrollView.width, height: scrollView.height)
        scrollView.contentSize = contentSize
        
        let contentView = UIView().addTo(scrollView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
        
        let textColor: UIColor = model.pageType == .news ? .systemBlue : .white
        let titleLabel = UILabel(text: model.title, font: UIFontMediumMake(17), textColor: textColor)
        titleLabel.addTo(contentView)
        titleLabel.numberOfLines = 0
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(16)
            make.top.equalToSuperview().inset(16)
        }
        
        if model.displayType == "text" {
            
            let contentLabel = UILabel()
            contentLabel.attributedText = model.attributedText
            contentLabel.addTo(contentView)
            contentLabel.numberOfLines = 0
            contentLabel.snp.makeConstraints { make in
                make.left.right.equalTo(titleLabel)
                make.top.equalTo(titleLabel.snp.bottom).offset(8)
            }
            
            contentView.setNeedsLayout()
            contentView.layoutIfNeeded()
            
            contentSize = CGSizeMake(view.width, contentLabel.maxY + tabBarSafeBottomMargin)
            scrollView.contentSize = contentSize
            contentView.snp.remakeConstraints { make in
                make.edges.equalToSuperview()
                make.size.equalTo(contentSize)
            }
        } else if let url = model.url, let Url = URL(string: url) {
            
            let imageView = UIImageView().addTo(contentView)

            let downloader = ImageDownloader.default
            downloader.downloadImage(
                with: Url,
                options: nil,
                progressBlock: { receivedSize, totalSize in
                    let progress = Double(receivedSize) / Double(totalSize)
                    print("下载进度: \(progress * 100)%")
                },
                completionHandler: { result in
                    switch result {
                    case .success(let value):
                        print("下载完成，图片大小: \(value.image.size)")
                        imageView.image = value.image
                        guard let image = imageView.image else { return }
                        
                        let showW = screenWidth - 32
                        let showH = image.size.height * showW / image.size.width
            
                        DispatchQueue.main.async {
                            imageView.snp.makeConstraints { make in
                                make.left.right.right.equalToSuperview().inset(16)
                                make.top.equalTo(titleLabel.snp.bottom).offset(8)
                                make.height.equalTo(showH)
                            }
                            
                            contentView.setNeedsLayout()
                            contentView.layoutIfNeeded()
                            
                            contentSize = CGSizeMake(self.view.width, imageView.maxY + tabBarSafeBottomMargin)
                            scrollView.contentSize = contentSize
                            contentView.snp.remakeConstraints { make in
                                make.edges.equalToSuperview()
                                make.size.equalTo(contentSize)
                            }
                        }
                    case .failure(let error):
                        print("下载失败: \(error)")
                    }
                }
            )
        }
 
    }
    
    func addWebView() {
        
        guard let url = model.url,  let pdfURL = URL(string: url) else {
            return
        }
        
        progressView.layer.cornerRadius = 1
        progressView.clipsToBounds = true
        navigationBar.contentView.addSubview(progressView)
        progressView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(2)
        }
                
        view.addSubview(webView)
        webView.alpha = 0
        webView.navigationDelegate = self
        webView.scrollView.backgroundColor = AppStyle.color.background
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        webView.snp.makeConstraints { make in
            make.left.right.right.equalToSuperview()
            make.top.equalTo(navBarHeight)
            make.bottom.equalToSuperview()
        }
        
        let request = URLRequest(url: pdfURL)
        webView.load(request)
    }
    
    deinit {
        if model.displayType == "pdf" {
            webView.removeObserver(self, forKeyPath: "estimatedProgress")
        }
     }
    
      override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?,
                                 context: UnsafeMutableRawPointer?) {
          if keyPath == "estimatedProgress" {
              if webView.estimatedProgress >= 1.0 {
                  self.progressView.setProgress(1, animated: true)
                  UIView.animate(withDuration: 0.35) {
                      self.progressView.alpha = 0
                  }
              } else {
                  progressView.progress = CGFloat(webView.estimatedProgress)
              }
          }
      }
    
    override var backIsCloseButton: Bool {
        return true
    }
}

extension NewsDetailController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.progressView.setProgress(1, animated: true)
        UIView.animate(withDuration: 0.5) {
            self.progressView.alpha = 0
        }
        UIView.animate(withDuration: 0.25) {
            webView.alpha = 1
        }
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        UIView.animate(withDuration: 0.1) {
            self.progressView.alpha = 0
        }
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        UIView.animate(withDuration: 0.1) {
            self.progressView.alpha = 0
        }
    }
}
